package www.wen.com.common.lib.data.entities.builtIn

import com.orhanobut.logger.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import www.wen.com.common.lib.util.RESPONSE_SUCCESS_CODE
import java.io.IOException

data class LazyEntity<out T>(val code: Int, val msg: String, val data: T)

/**
 * 通用json模板
 */
suspend fun <T> LazyEntity<T>.executeResponse(
    successBlock: (suspend CoroutineScope.() -> Unit)? = null,
    errorBlock: (suspend CoroutineScope.() -> Unit)? = null
): Result<T> {
    return kotlinx.coroutines.coroutineScope {
        if (code != RESPONSE_SUCCESS_CODE ) {
            errorBlock?.let { it() }
            Result.Error(IOException(msg), code)
        } else {
            successBlock?.let { it() }
            Result.Success(data)
        }
    }
}

//-----以下是兼容其他样式的模板

data class LazyPageEntity<out T>(val code: Int, val message: String,val detail:String, val data: Page<T>)

data class Page<out T>(val pagedData:List<T>,val pagination: Pagination)

data class Pagination(val pageIndex:Int,val pageSize:Int,val totalCount:Int)

suspend fun <T> executePageResponse(
    response: LazyPageEntity<T>,
    successBlock: (suspend CoroutineScope.() -> Unit)? = null,
    errorBlock: (suspend CoroutineScope.() -> Unit)? = null
): Result<Page<T>> {
    return coroutineScope {
        if (response.code != RESPONSE_SUCCESS_CODE) {
            errorBlock?.let { it() }
            Logger.i("Exception = ${response.message}")
            Result.Error(IOException(response.message))
        } else {
            successBlock?.let { it() }
            Result.Success(response.data)
        }
    }
}
